// 图片懒加载
const lazy = {
	mounted(el, binding) {
		const observer = new IntersectionObserver((entries) => {
			if (entries[0].isIntersecting) {
				el.src = binding.value;
				observer.unobserve(el);
			}
		});
		observer.observe(el);
	}
}

// 防抖
const debounce = {
	mounted(el, binding) {
		const {
			value,
			modifiers
		} = binding;
		const events = modifiers.input ? ['input'] : [];
		if (modifiers.click) events.push('click');
		let timeoutId;
		const handler = (event) => {
			if (timeoutId) clearTimeout(timeoutId);
			timeoutId = setTimeout(() => {
				value(event); //event 是触发事件的对象，可以回传给你的触发事件
			}, 500); // 默认防抖时间为300毫秒
		};

		events.forEach((event) => {
			el.addEventListener(event, handler);
		});

		// 清理函数，防止内存泄漏
		el._vueDebounceHandler = handler;
	},
	unmounted(el) {
		if (el._vueDebounceHandler) {
			['input', 'click'].forEach((event) => {
				el.removeEventListener(event, el._vueDebounceHandler);
			});
		}
	}
};

// 节流
const throttle = {
	mounted(el, binding) {
		let timeoutId;
		el.addEventListener('input', (event) => {
			if (timeoutId) clearTimeout(timeoutId);
			timeoutId = setTimeout(() => {
				binding.value(event);
			}, 300);
		});
	}
}
// 复制文本到剪贴板
const copy = {
	mounted(el, binding) {
		el.addEventListener('click', () => {
			navigator.clipboard.writeText(el.innerText).then(() => {}).catch(err => {
			});
		});
	}
}
const hiddentext = {
	mounted(el, binding) {
		if (!el.innerText) {
			return
		}
		if (binding.modifiers.phone) {
			el.innerText = el.innerText.replace(/(\d{3})\d{4}(\d{4})/, '$1****$2')
		}
		if (binding.modifiers.cardId) {
			el.innerText = el.innerText.replace(/(\d{4})\d{10}(\d{4})/, '$1*********$2')
		}
	}
}

export default {
	lazy,
	debounce,
	throttle,
	copy,
	hiddentext
}